package com.hw.one.transpot.fileupload.util;
import com.hw.one.transpot.fileupload.constant.Constant;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

//文件上传客户端
public class FileTransportClientUtil {

    EventLoopGroup group = null;
    public void connect(String ip, int port, String transferFilePath)  {
        try {
            group = new NioEventLoopGroup();
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline().addLast(new ObjectEncoder());
                            ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
                            ch.pipeline().addLast(new FileTransportClientHandler(transferFilePath));
                        }
                    });
            ChannelFuture f = b.connect(ip, port).sync();
            f.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
    public void shutdown(){
        if(null != group){
            group.shutdownGracefully();
            group = null;
        }
    }

//    public static void main(String[] args) throws InterruptedException {
//        long start = System.currentTimeMillis();
//        new FileTransportClientUtil().connect(FILE_IP, FILE_PORT, null);
//        System.out.println(System.currentTimeMillis() - start);
//    }


    public static final int FILE_PORT = Constant.PORT;
    public static final String FILE_IP = Constant.IP;
}
